import {
  Body1Stronger,
  Button,
  FluentProvider,
  Input,
  InputOnChangeData,
  Label,
  Spinner,
  Textarea,
  webDarkTheme,
  webLightTheme,
} from '@fluentui/react-components'
import { invoke } from '@tauri-apps/api'
import { useEffect, useRef, useState } from 'react'

export default function App() {
  const [theme, setTheme] = useState(webLightTheme)
  const [errMsg, setErrMsg] = useState('')
  const [stand, setStand] = useState('300')
  const lastStand = useRef('300')
  const [float, setFloat] = useState('250')
  const lastFloat = useRef('250')
  const [counter, setCounter] = useState(-1)
  const [buttonDisabled, setButtonDisabled] = useState(false)
  
  // 新增状态
  const [question, setQuestion] = useState('')
  const [answer, setAnswer] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [profession, setProfession] = useState('')
  const [subject, setSubject] = useState('')
  const [apiKey, setApiKey] = useState('')

  // 读取本地存储的API密钥
  useEffect(() => {
    const savedApiKey = localStorage.getItem('apiKey');
    if (savedApiKey) {
      setApiKey(savedApiKey);
    }
  }, []);

  // 保存API密钥到本地存储
  useEffect(() => {
    if (apiKey) {
      localStorage.setItem('apiKey', apiKey);
    } else {
      localStorage.removeItem('apiKey');
    }
  }, [apiKey]);
  
  const onChange = (
    set: React.Dispatch<React.SetStateAction<string>>,
    _event: React.ChangeEvent<HTMLInputElement>,
    data: InputOnChangeData
  ) => {
    set(data.value)
  }
  
  const onBlur = (
    current: string,
    set: React.Dispatch<React.SetStateAction<string>>,
    last: React.MutableRefObject<string>
  ) => {
    if (/^[1-9]\d{0,5}$/.test(current)) {
      last.current = current
    } else {
      set(last.current)
    }
  }
  
  const onClick = () => {
    setButtonDisabled(true)
    setCounter(3)
    const interval = setInterval(() => {
      setCounter((counter: number) => {
        if (counter == 1) {
          clearInterval(interval)
          ;(async () => {
            try {
              await invoke('paste', {
                content: answer,
                stand: parseInt(lastStand.current),
                float: parseInt(lastFloat.current),
              })
              setErrMsg('')
            } catch (e) {
              setErrMsg(e as string)
            }
            setButtonDisabled(false)
            setCounter(-1)
          })()
          return 0
        }
        return counter - 1
      })
    }, 1000)
  }

  // AI请求函数
  const handleAskAI = async () => {
    if (!question.trim()) {
      setErrMsg('请输入问题');
      return;
    }
    
    setIsLoading(true);
    setAnswer('');
    
    try {
      const result = await invoke('ask_ai', {
        question: question.trim(),
        profession: profession.trim(),
        subject: subject.trim(),
        apiKey: apiKey.trim() // 将 api_key 改为 apiKey
      });
      setAnswer(result as string);
      setErrMsg('');
    } catch (e) {
      setErrMsg(e as string);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)')
    setTheme(mediaQueryList.matches ? webDarkTheme : webLightTheme)
    const listener = (event: MediaQueryListEvent) => {
      setTheme(event.matches ? webDarkTheme : webLightTheme)
    }
    mediaQueryList.addEventListener('change', listener)
    return () => {
      mediaQueryList.removeEventListener('change', listener)
    }
  }, [])

  return (
    <FluentProvider
      style={{
        width: '100%',
        height: '100%',
      }}
      theme={theme}>
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          padding: 20,
          boxSizing: 'border-box',
          overflow: 'hidden',
        }}>
        {/* 顶部标题区 */}
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: 15
        }}>
          <Body1Stronger>
            {errMsg ? (
              <span style={{ color: '#d13438' }}>{errMsg}</span>
            ) : (
              "作业辅助神器"
            )}
          </Body1Stronger>
        </div>

        {/* 专业科目设置区 */}
        <div style={{ 
          display: 'flex', 
          flexWrap: 'wrap',
          gap: '15px',
          marginBottom: 15 
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Label weight="semibold" style={{ marginRight: '5px', minWidth: '50px' }}>专业:</Label>
            <Input
              value={profession}
              size="small"
              style={{ width: '120px' }}
              onChange={(_, data) => setProfession(data.value)}
              placeholder="如: 计算机"
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Label weight="semibold" style={{ marginRight: '5px', minWidth: '50px' }}>科目:</Label>
            <Input
              value={subject}
              size="small"
              style={{ width: '120px' }}
              onChange={(_, data) => setSubject(data.value)}
              placeholder="如: 编程"
            />
          </div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Label weight="semibold" style={{ marginRight: '5px', minWidth: '50px' }}>API密钥:</Label>
            <Input
              value={apiKey}
              size="small"
              style={{ width: '250px' }}
              onChange={(_, data) => setApiKey(data.value)}
              placeholder="输入你的API密钥"
            />
            <span style={{ marginLeft: '5px', color: '#666', fontSize: '12px' }}>（获取方式：访问<a href="https://platform.deepseek.com/usage" target="_blank">DeepSeek开放平台</a>申请API密钥）</span>
          </div>
        </div>

        {/* 问题输入区 */}
        <div style={{ marginBottom: 15 }}>
          <Label htmlFor="question" weight="semibold">问题:</Label>
          <Textarea 
            id="question"
            value={question} 
            onChange={(_: any, data: any) => setQuestion(data.value)}
            style={{ width: '100%', minHeight: '80px' }}
            placeholder="输入你的问题..."
          />
          <Button 
            appearance="primary"
            onClick={handleAskAI}
            disabled={isLoading || !question.trim()}
            style={{ marginTop: 10 }}
          >
            {isLoading ? <Spinner size="tiny" /> : '获取回答'}
          </Button>
        </div>

        {/* AI回答区 */}
        <div style={{ 
          flex: '1 1 auto',
          display: 'flex', 
          flexDirection: 'column', 
          marginBottom: 15 
        }}>
          <Label htmlFor="answer" weight="semibold">AI回答:</Label>
          <Textarea 
            id="answer"
            value={answer} 
            onChange={(_: any, data: any) => setAnswer(data.value)}
            style={{ 
              width: '100%', 
              minHeight: '250px', 
              maxHeight: '400px',
              overflow: 'auto', 
              whiteSpace: 'pre-wrap',
              wordBreak: 'break-word',
              resize: 'vertical',
              flex: '1 1 auto',
              fontFamily: 'sans-serif',
              fontSize: '14px',
              lineHeight: '1.5'
            }}
            placeholder="AI回答将显示在这里..."
            readOnly={false}
          />
        </div>

        {/* 打字设置区 */}
        <div style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 15,
        }}>
          <div style={{ display: 'flex', gap: '15px' }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Label weight="semibold">基本延迟:</Label>
              <Input
                value={stand}
                size="small"
                style={{ marginLeft: 8, width: '60px' }}
                onChange={onChange.bind(null, setStand)}
                onBlur={onBlur.bind(null, stand, setStand, lastStand)}
              />
            </div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Label weight="semibold">浮动值:</Label>
              <Input
                value={float}
                size="small"
                style={{ marginLeft: 8, width: '60px' }}
                onChange={onChange.bind(null, setFloat)}
                onBlur={onBlur.bind(null, float, setFloat, lastFloat)}
              />
            </div>
          </div>
          
          <Button
            appearance="primary"
            disabled={buttonDisabled || !answer.trim()}
            onClick={onClick}
            size="large"
            style={{ minWidth: '100px' }}
          >
            {counter == -1 ? (
              '粘贴'
            ) : counter == 0 ? (
              <Spinner size="tiny" />
            ) : (
              counter
            )}
          </Button>
        </div>
      </div>
    </FluentProvider>
  )
}
